package pay.serviceImpl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import pay.common.HqlFilter;
import pay.entity.Parameter;
import pay.service.IParameter;
import pay.serviceImpl.dao.base.impl.BaseServiceImpl;
import pay.utils.JsonUtils;
import pay.utils.RedisCilent;
import pay.utils.StringHelper;

import java.util.ArrayList;
import java.util.List;

@Service
public class ParameterImpl extends BaseServiceImpl<Parameter> implements IParameter {

	private Logger logger = LoggerFactory.getLogger(ParameterImpl.class);
	@Override
	public Parameter findById(long id) {
		
		return getById(id);
	}

	@Override
	public void add(Parameter u) {
		
		RedisCilent.setString(u.getName(), JsonUtils.toJson(u));
		
		super.save(u);
	}

	@Override
	public void delete(Parameter u) {
		delete(u);
	}

	@Override
	public void update(Parameter u) {

		super.update(u);

		RedisCilent.setString(u.getName(), JsonUtils.toJson(u));

	}

	@Override
	public Parameter getByName(String name) {
		Parameter parm = null;
		
		//如果参数没有存在Redis中，则将其存入redis中
		if (!RedisCilent.existsKey(name)) {
			//logger.info(name + "not in the redis" );

			HqlFilter hqlfilter = new HqlFilter();
			hqlfilter.addEQFilter("name", name);
			List<Parameter> parmList = new ArrayList<Parameter>();
			parmList = this.findByFilter(hqlfilter);


			if(parmList != null && parmList.size() > 0){
				parm = parmList.get(0);
			}
			
			RedisCilent.setString(name, JsonUtils.toJson(parm));

			 
		}
		
		//读取Redis中的参数
		String parmStr = RedisCilent.getString(name);

		if(StringHelper.isNotEmpty(parmStr)){
			parm = JsonUtils.toBean(parmStr,  Parameter.class);
		}

		return parm;
	}
	
	@Override
	public List<Parameter> getByFlag(String flag) {
		HqlFilter hqlfilter = new HqlFilter();
		hqlfilter.addEQFilter("flag", flag);
		List<Parameter> parmList = new ArrayList<Parameter>();
		parmList = this.findByFilter(hqlfilter);
		 
		
		return parmList;
	}

	@Override
	public Boolean existByName(String name) {
		Parameter parm = getByName(name);
		return parm != null?true:false;
	}

	@Override
	public List<Parameter> findByFilter(HqlFilter hqlFilter, Integer curPage,
			Integer pageSize) {
		 
		return super.findByFilter(hqlFilter, curPage, pageSize);
	}

 
}
